#!/usr/bin/env perl

# vim: ts=4:sw=4:et:syntax=perl
BEGIN {
    push @INC,"../libs";
}

# This is a test server - it will load in the following details:
# Public key(s) = from server/pubkeys/*.public

use gri2_rsatcp;
use Data::Dumper;
use Socket;
use Carp;

# $::private=undef;
# {
    # my ($a,$b)=gri2_rsatcp::load_private_key({file=>"server/privkeys/server.private"});
    # if(!$a) {
        # print STDERR "$_\n" foreach(@$b);
        # exit(1);
    # }
    # $::private=$b;
# }

# Load all public keys from expected directory...

$::publics=undef;
{
    my ($a,$b,$c)=gri2_rsatcp::load_all_public_keys({dir=>"server/pubkeys"});
    if(!$a) {
        print STDERR "$_\n" foreach(@$b);
        exit(1);
    }
    $::publics=$b;
}

print Dumper($::publics);
# Ok for our testing we create a socket on port 44422 and
# listen for connections. 
{
    my $port=44422;
    my $proto = getprotobyname('tcp');
    socket(Server, PF_INET, SOCK_STREAM, $proto) or die;
    setsockopt(Server, SOL_SOCKET, SO_REUSEADDR, pack("l", 1)) or die;
    bind(Server, sockaddr_in($port, INADDR_ANY)) or die;
    listen(Server,SOMAXCONN) or die;

    # Main LOOP...
    my $client_fd;
    for ( ; $paddr = accept($client_fd,Server); close $client_fd) {
        my($port,$iaddr) = sockaddr_in($paddr);
        my $name = gethostbyaddr($iaddr,AF_INET);

        # read in the request...
        my ($a,$b,$c)=gri2_rsatcp::server_recv_data({
            fd=>$client_fd, 
            pub_keys=>$::publics,
        });
        if(! $a) {
            print STDERR "Error: $_\n" foreach(@$b); next;
        }
        print "Session key: $b\n";
        print "Request    : $c\n";

        my $session_key=$b;
        my $request=$c;
        # Now we have a session key we can send a response ... 

        my $response="Same to you: $request";
        ($a,$b)=gri2_rsatcp::server_send_data({
            fd=>$client_fd,
            session_key=>$session_key,
            message=>$response
        });
        if(!$a) {
            print STDERR "Error: $_\n" foreach(@$b); next;
        } else {
            print "Message sent successfully.\n";
        }
    }
}

